package com.xiaoming.tranAnno.service.impl;

import com.xiaoming.tranAnno.aop.MyTransactional;
import com.xiaoming.tranAnno.dao.UserMapper;
import com.xiaoming.tranAnno.entity.User;
import com.xiaoming.tranAnno.service.UserService;
import com.xiaoming.tranAnno.utils.TransactionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class UserServiceImpl implements UserService {

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public TransactionUtil transactionUtil;

    @Override
    public List<User> getUserById(Integer id) {
        return null;
    }


    /**
     * 不使用自定义注解和Spring的Transactional注解的话
     * 可以使用手动事务的方式来控制事务的提交和回滚
     *
     * @return
     */
/*    @GetMapping("/saveUser")
    @Override
    public String saveUser() {
        User user = new User(1, "xiaoming");
        TransactionStatus transaction = null;
        try {
            transaction = transactionUtil.begin();
            Integer result = userMapper.saveUser(user);
            int i = 1 / 0;
            transactionUtil.commit(transaction);
            return "SUCCESS";
        } catch (Exception e) {
            transactionUtil.rollback(transaction);
            return "FAILED";
        }
    }*/


    /**
     * 下面这种做法为使用自定义注解的做法
     * @return
     */
    @GetMapping("/saveUser")
    @MyTransactional
    @Override
    public String saveUser() {
        User user = new User(1, "xiaoming");
        TransactionStatus transaction = null;
            Integer result = userMapper.saveUser(user);
            int i = 1 / 0;
            return "SUCCESS";
    }
}
